package com.tuanzi.loan.business.repository.system.impl;

import com.tuanzi.loan.business.repository.system.custom.AdvertiseRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.vo.request.system.AdvertiseSearchRequest;
import com.tuanzi.loan.vo.response.system.AdvertiseSearchResponse;
import org.jooq.Record;
import org.jooq.RecordMapper;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import static com.tuanzi.loan.generated.jooq.loan.tables.LoanAdsChannelDetail.LOAN_ADS_CHANNEL_DETAIL;

/**
 * @author Ray 2017/09/21
 */
@SuppressWarnings({ "rawtypes" })
public class AdvertiseRepositoryImpl extends JOOQBaseRepository implements AdvertiseRepositoryCustom {

	@Override
	protected TableImpl getTable() {
		return LOAN_ADS_CHANNEL_DETAIL;
	}

	@Override
	public Page<AdvertiseSearchResponse> list(AdvertiseSearchRequest searchRequest, Pageable pageable) {

		contains(LOAN_ADS_CHANNEL_DETAIL.ACCOUNT_ID, searchRequest.getAccountId());
		contains(LOAN_ADS_CHANNEL_DETAIL.CHANNEL_CODE, searchRequest.getChannel());
		if(searchRequest.getAdsPlatformType() != null && searchRequest.getAdsPlatformType() != 1000) {
			eq(LOAN_ADS_CHANNEL_DETAIL.ADS_PLATFORM_TYPE, searchRequest.getAdsPlatformType());
	}
		contains(LOAN_ADS_CHANNEL_DETAIL.EVENT_TYPE, searchRequest.getEventType());
		orderBy(LOAN_ADS_CHANNEL_DETAIL.ID, Sort.Direction.ASC);
		return search(pageable, new AdvertiseSearchResponseRecordMapper());
	}

	private final class AdvertiseSearchResponseRecordMapper implements RecordMapper<Record, AdvertiseSearchResponse> {

		@Override
		public AdvertiseSearchResponse map(Record record) {
			AdvertiseSearchResponse response = new AdvertiseSearchResponse();
			response.setId(record.get(LOAN_ADS_CHANNEL_DETAIL.ID));
			response.setAccountId(record.get(LOAN_ADS_CHANNEL_DETAIL.ACCOUNT_ID));
			response.setAccountpwd(record.get(LOAN_ADS_CHANNEL_DETAIL.ACCOUNT_PWD));
			response.setChannel(record.get(LOAN_ADS_CHANNEL_DETAIL.CHANNEL_CODE));
			response.setAccessToken(record.get(LOAN_ADS_CHANNEL_DETAIL.ACCESS_TOKEN));
			response.setRefreshToken(record.get(LOAN_ADS_CHANNEL_DETAIL.REFRESH_TOKEN));
			response.setAppId(record.get(LOAN_ADS_CHANNEL_DETAIL.APP_ID));
			response.setAppSecret(record.get(LOAN_ADS_CHANNEL_DETAIL.APP_SECRET));
			response.setUserActionSetId(record.get(LOAN_ADS_CHANNEL_DETAIL.USER_ACTION_SET_ID));
			response.setActionType(record.get(LOAN_ADS_CHANNEL_DETAIL.ACTION_TYPE));
			response.setAdsPlatformType(record.get(LOAN_ADS_CHANNEL_DETAIL.ADS_PLATFORM_TYPE));
			response.setEventType(record.get(LOAN_ADS_CHANNEL_DETAIL.EVENT_TYPE));
			return response;
		}
	}
}
